var ssName = RequestURLParam.getParam("sessionStrogeName") || "ktfTest"
var index = parent.layer.getFrameIndex(window.name);
var dst = '#ouTree'
var authtree, form, layer, table, yutons_sug
var returnObj = {
    "optype": "cancel",
    "ids": [],
    "objs": []
}

var ssdata = sessionStorage.getItem(ssName)
if (ssdata && ssdata != undefined && ssdata != "undefined") {
    ssdata = ssdata.replace("[", "")
    ssdata = ssdata.replace("]", "")
    ssdata = "[" + ssdata + "]"

    console.log(ssdata)
    returnObj.ids = JSON.parse(ssdata)
}

layui.config({
    base: '/static/lib/layuiadmin/',
}).extend({
    authtree: 'modules/czh_authtree',
}).extend({
    yutons_sug: 'modules/yutons_sug_zm',
}).use(['jquery', 'authtree', 'form', 'layer', 'yutons_sug']);


layui.use(['jquery', 'authtree', 'form', 'layer', 'table', 'yutons_sug'], function () {
    authtree = layui.authtree;
    form = layui.form;
    layer = layui.layer;
    table = layui.table;
    yutons_sug = layui.yutons_sug;

    loadOrgAndUsers()
    loadTable(0)
    renderSearcher()

    //监听行工具事件
    table.on('tool(selectedUser)', function(obj){
        var rowData = obj.data;
        if(obj.event === 'unselect'){
            returnObj.ids.splice(returnObj.ids.indexOf(rowData.id),1)
            loadTable(1)

            $("input[authoritytype='5'][value=5-" + rowData.id + "]").each(function (i, iDom) {
                if ($(iDom).next().hasClass("layui-form-checked")) {
                    $(iDom).click()
                }
            })

            form.render()
        }
    });
});

function loadOrgAndUsers() {
    ActHttpRequest('/wf/privilege/list', {}, function (resData) {
        if (resData.code != 200) return

        var treeList = resData.list

        loadchecked(resData)

        authtree.render(dst, treeList, {
            nameKey: "name",
            childKey: "list",
            checkType: 'checkbox',
            valueKey: 'value',
            layfilter: 'chkUser',
            openchecked: true,
            openall: false
        });



        form.on('checkbox(chkUser)', function (thisData) {
            // 注意这里：需要等待事件冒泡完成，不然获取叶子节点不准确。

            returnObj.ids.length = 0
            setTimeout(function () {
                var leaf = authtree.getLeaf('#ouTree');
                var lastChecked = authtree.getLastChecked('#ouTree');
                var lastNotChecked = authtree.getLastNotChecked('#ouTree');

                leaf.forEach(function (item) {
                    if ($('input[value=' + item + ']').attr("authoritytype") == "5") {

                        i = parseInt(item.substr(2))

                        if (returnObj.ids.indexOf(i) < 0) {
                            returnObj.ids.push(i)
                        }
                    }
                })

                // console.log(returnObj.ids)
                loadTable(1)
            }, 100);
        });


    }, 'post', null, null, '保存中。。。', false);
}

function clearList() {
    returnObj.ids = []
    loadTable(1)
    authtree.uncheckAll(dst)
}

function cancel() {
    sessionStorage.setItem(ssName, JSON.stringify(returnObj))
    parent.layer.close(index);
}

function sendData() {
    returnObj.optype = "ok"
    sessionStorage.setItem(ssName, JSON.stringify(returnObj))
    cancel()
}

function loadTable(optype) {
    var userIds = JSON.stringify(returnObj.ids)
    userIds = userIds.replace("[","")
    userIds = userIds.replace("]","")

    $.ajax({
        url: '/sys-user/getUserListFromIds',
        data: {"userIds": userIds},
        type: 'get',
        async: false,
        success: function (resData) {
            // console.log(resData)
            returnObj.objs = resData.userList
        }
    })

    if (optype == 1) {
        table.reload('selectedUser', {
            data: returnObj.objs
        });

        return
    }

    table.render({
        elem: '#selectedUser'
        ,height: 'full-98'
        ,data: returnObj.objs
        ,limit: 9999
        ,cols:  [[
            ,{field:'id', hide: 'true'}
            ,{field:'name', width:'100', fixed: 'left', title: "已选用户", align: "center"}
            ,{field:'orgName', width:'254', title: "机构", align: "center"}
            ,{field:'right', width:'70', title: "操作", toolbar: '#barUnselect', align: "left"}
        ]]
    });

}



function loadchecked(listItem) {
    if (listItem.hasOwnProperty("list") && listItem.list.length > 0) {
        listItem.list.forEach(function (item) {
            loadchecked(item)
        })
    } else {
        if (listItem.hasOwnProperty("authorityType") && listItem.authorityType == "5") {
            if (listItem.hasOwnProperty("value")) {
                if (returnObj.ids.indexOf(parseInt(listItem.value.substr(2))) > -1) {
                    listItem.checked = true
                }
            }
        }
    }


}

function renderSearcher() {

    yutons_sug.render({
        id: "searchUser", //设置容器唯一id
        type: 'sug', //设置输入框提示类型：sug-下拉框，sugTable-下拉表格
        url: "/sys-user/listKey?key=" //设置异步数据接口,url为必填项
    });

}

function ssselect() {
    var strVal = $("#searchUser").val()
    if (!strVal) return

    var info = strVal.split(" - ")
    if (info.length == 3) {
        var uid = parseInt(info[1])
        if (uid && returnObj.ids.indexOf(uid) < 0) returnObj.ids.push(uid)
        loadTable(1)

        $("input[authoritytype='5'][value=5-" + uid + "]").each(function (i, iDom) {
            if (!$(iDom).next().hasClass("layui-form-checked")) {
                $(iDom).click()
            }
        })

        form.render()
    }
}
